package com.bao.system.service.impl;

import com.bao.system.entity.BUser;
import com.bao.system.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    /*自动注入编写的 Mapper */
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if(username == null){
            throw new RuntimeException("用户名不能为空");
        }
        LambdaQueryWrapper<BUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BUser::getUsername, username);
        BUser user = userMapper.selectOne(wrapper);
        System.out.println(user);

        if(user == null) {
            System.out.println("不存在");
            throw new UsernameNotFoundException(String.format("%s用户不存在",username));
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> codeList = userMapper.getRoleCodeByUserName(username);
        codeList.forEach(code ->{
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(code);
            authorities.add(authority);
        });
        return new User(user.getUsername(),user.getPassword(),authorities);

    }
}
